package com.mioto.ld.communication;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import com.mioto.ld.communication.mqtt.MqttClientConnect;
import com.mioto.ld.communication.mqtt.protocol.model.PType;
import org.springframework.stereotype.Component;

/**
 * @author mioto-qinxj
 * @date 2024/5/16
 * @desc 操作mqtt-websocket客户端缓存
 */
@Component
public class CommunicationCache {

    /**
     * 创建缓存，默认30秒过期
     * key- 设备(sn) + _ + 控制类型(ptype)
     * value-websocket clientId
     */
    private TimedCache<String, String> timedCache = CacheUtil.newTimedCache(30000);

    public void put(String sn,String sendPtype,String clientId){
        timedCache.put(buildKey(sn,sendPtype),clientId);
    }

    public String getClientId(String sn,String replyPtype){
        return timedCache.get(buildKey(sn,PType.getSendPtype(replyPtype)));
    }

    private String buildKey(String sn,String sendPtype){
        return StrBuilder.create(sn).append(StrUtil.UNDERLINE).append(sendPtype).toString();
    }
}
